<?php

namespace App\Imports;

use App\Models\Local\UserModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ImportsExcel
    implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading
{
    public $batchSize = 1000;
    public $chunkSize = 1000;
    public $format;
    public $mod;
    public function __construct($format, Model $mod)
    {
        $this->format = $format;
        $this->mod = $mod;
    }

    public function model(array $row)
    {
        dump($row) ;

        $insert = [];
        foreach ($this->format as $k => $v) {
            $insert[$k] = $row[$v];
        }
//        return new UserModel($insert);
        try {
            $this->mod->create($insert);
            return [];
        } catch (\Exception $e) {
            Log::channel('jobLog')->error('导入失败:'.json_encode($insert));
            return [];
        }
    }

    /**
     * 指定查询数量
     * @return int
     */
    public function batchSize(): int
    {
        return $this->batchSize;
    }

    /**
     * 分块读取excel
     * @return int
     */
    public function chunkSize(): int
    {
        return $this->chunkSize;
    }

}
